﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharePoint.Security.ConfigAnalyzer.Engine.Base;
using SharePoint.Security.ConfigAnalyzer.Engine.Common;
using Microsoft.SharePoint.Administration;

namespace SharePoint.Security.ConfigAnalyzer.Engine.Rules.Others
{
    public class AppPollAccounts : Base.BaseRule
    {
        public AppPollAccounts()
        {
            RuleInfo = new RuleInfo
            {
                Title = "Application Pools for Web Apps",
                Description = "Each Web Application should have its own Application Pool",
                ExpectedValue = "True"
            };
        }

        #region Overrides of BaseRule

        public override void Validate()
        {
            //List<SPWebApplication> webApps = Helper.GetWebApps();
            List<Guid> appAcctIds = new List<Guid>();
            var logger = Logger.Log;
            bool appPoolDoesNotExist = true;

            SPFarm farm = ObjectHelper.Farm;
            foreach (SPService objService in farm.Services)
            {
                if (objService is SPWebService)
                {
                    SPWebService oWebService = (SPWebService)objService;
                    foreach (SPWebApplication oWebApplication in oWebService.WebApplications)
                    {
                        SPApplicationPool appPool = oWebApplication.ApplicationPool;
                        if (appAcctIds.Contains(appPool.Id))
                        {
                            logger.Error(string.Format("Application Pools for Web Apps - '{0}' account is used by more than one web application", appPool.DisplayName));                            
                            appPoolDoesNotExist = false;
                        }
                        else
                        {
                            appAcctIds.Add(appPool.Id);
                        }
                    }
                }
            }

            if (appPoolDoesNotExist)
            {
                CurrentValue = appPoolDoesNotExist.ToString();
                Status = Status.Pass;          
            }
            else
            {
                CurrentValue = appPoolDoesNotExist.ToString() + ". Refer log file for more info";
                Status = Status.Fail;
            }

        }

        #endregion

    }   
}
